<template>
    <el-aside width="260px" class="pt-2 pb-0">
        <div class="image-category" :style="{ height: cHeight + 'px' }">
            <div class="image-category-item" v-for="(item, index) in catogeries"
                :class="{ active: item.id == current ? true : false }" :key="index" @click="onSelect(item.id)">
                <span class="ml-5 text-gray-600 text-sm">{{ item.name }}</span>
                <el-button class="px-1 py-0 h-[28px] ml-auto" @click="onEdit(item.id)"><el-icon>
                        <Edit />
                    </el-icon></el-button>
                <el-button class="icon-btn" @click.stop="onDelete(item.id)" v-loading.fullscreen.lock="loading"><el-icon>
                        <Close />
                    </el-icon></el-button>
            </div>
        </div>
        <div style="height: 50px;" class="flex items-center justify-center">
            <el-pagination layout="prev, next" :current-page="currentPage" :total="total" :page-size="limit"
                @current-change="onPageChange" />
        </div>
    </el-aside>
    <FormDrawer ref="drawerRef" :title="drawerTitle" @submit="onSubmit">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100">
            <el-form-item label="相册名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入相册名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="排序" prop="order">
                <el-input-number v-model="form.order" :min="1" :max="1000" />
            </el-form-item>
        </el-form>
    </FormDrawer>
</template>
<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { getImageCategores, getImagesByCatogeryId, updateCatogeryById, addCatogery, deleteCatogery } from '../api/image'
import { toast, showModel } from "../composables/util"
import FormDrawer from './FormDrawer.vue'

const props = defineProps({
    cHeight: Number
})

const current = ref(0)

const onSelect = (id) => {
    // console.log(id)
    if (current.value != id) {
        current.value = id
    }
}


const addCatoyery = () => {
    drawerRef.value.open()
    drawerTitle.value = "新增相册"
    form.id = 0
}

// 组件loading状态
const loading = ref(false)

// 定义本组件对外包括的方法或属性
defineExpose({ current, addCatoyery })

// 定义事件
const emit = defineEmits(["current-change"])

// 监听current 如果current发生变化，则出发change事件
watch(() => current.value, () => emit('current-change', current.value))


// 获取图片分类数据
const catogeries = ref(null)
const total = ref(0) // 分类总记录数
const limit = ref(10) // 每页显示的条数
const currentPage = ref(1) // 当前页码
onMounted(() => {
    currentPage.value = 1
    getData()
})

const getData = () => {
    getImageCategores(currentPage.value, limit.value).then(res => {
        catogeries.value = res.data.list
        if (res.data.list.length > 0) {
            // 默认选中第一个
            current.value = res.data.list[0].id
            total.value = res.data.totalCount
        }
    })
}

const onPageChange = (newPaegIndex) => {
    currentPage.value = newPaegIndex
    getData()
}

// 编辑页面
const drawerTitle = ref('')
const drawerRef = ref(null)

const onEdit = (id) => {
    drawerRef.value.open()
    drawerTitle.value = "编辑相册"
    let item = catogeries.value.find(i => i.id == id)
    form.id = item.id
    form.name = item.name
    form.order = item.order
}

const onDelete = (id) => {
    let item = catogeries.value.find(i => i.id == id)
    showModel("确定删除相册：" + item.name + "吗？").then(res => {
        loading.value = true
        deleteCatogery(id).then(res => {
            toast("删除相册成功")
            getData()
        }).catch(err => {
            // do nothing
        }).finally(() => {
            // hideFullLoading()
            loading.value = false
        })
    })
}

// do not use same name with ref
const form = reactive({
    id: 0,
    name: '',
    order: 50,
})

const rules = {
    name: [{ required: true, message: '相册名称不能为空', trigger: 'blur' }],
    order: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
}

const formRef = ref(null)
const onSubmit = (e) => {
    formRef.value.validate(async valid => {
        if (!valid) {
            return false
        }
        drawerRef.value.showLoading()

        if (form.id > 0) {
            updateCatogeryById(form.id, form.name, form.order).then(res => {
                toast("修改相册成功")
                getData()
            }).catch(err => {
                // do nothing
            }).finally(() => {
                clearFormAndClose()
            })
        } else {
            addCatogery(form.name, form.order).then(res => {
                toast("新增相册成功")
                getData()
            }).catch(err => {
                // do nothing
            }).finally(() => {
                clearFormAndClose()
            })
        }
    })
}

// 新增、修改完毕后对form进行清空处理
const clearFormAndClose = () => {
    drawerRef.value.hideLoading()
    drawerRef.value.close()
    form.id = 0
    form.name = ''
    form.order = 50
}



</script>

<style scoped>
.image-category {
    overflow-y: auto
}

.image-category-item {
    @apply flex justify-between items-center h-[40px];
}

.image-category-item:hover,
.image-category .active {
    background: #eeeeee;
}

.image-category-item .icon-btn {
    @apply px-1 py-0 h-[28px] mr-5;
}
</style>